import { Application } from "egg";

export default (app: Application) => {
  const { STRING, INTEGER, DATE, ENUM, DECIMAL, TEXT } = app.Sequelize;

  const Donation = app.model.define(
    "Donation",
    {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      projectId: {
        type: INTEGER,
        allowNull: false,
        comment: "项目ID",
      },
      donorId: {
        type: INTEGER,
        allowNull: false,
        comment: "捐款人ID",
      },
      amount: {
        type: DECIMAL(20, 2),
        allowNull: false,
        comment: "捐款金额",
      },
      currency: {
        type: ENUM("ETH", "USDT", "CNY"),
        defaultValue: "ETH",
        comment: "捐款币种",
      },
      transactionHash: {
        type: STRING(100),
        allowNull: true,
        comment: "区块链交易哈希",
      },
      blockNumber: {
        type: INTEGER,
        allowNull: true,
        comment: "区块号",
      },
      status: {
        type: ENUM("pending", "confirmed", "failed"),
        defaultValue: "pending",
        comment: "交易状态",
      },
      message: {
        type: TEXT,
        allowNull: true,
        comment: "捐款留言",
      },
      isAnonymous: {
        type: INTEGER,
        defaultValue: 0,
        comment: "是否匿名捐款",
      },
      donorName: {
        type: STRING(100),
        allowNull: true,
        comment: "捐款人姓名（匿名时使用）",
      },
      confirmedAt: {
        type: DATE,
        allowNull: true,
        comment: "确认时间",
      },
    },
    {
      tableName: "donations",
      timestamps: true,
      paranoid: true,
      underscored: true,
    }
  );

  // 关联关系
  Donation.associate = function (): void {
    // 捐款属于一个项目
    app.model.Donation.belongsTo(app.model.Project, {
      foreignKey: "projectId",
      as: "project",
    });

    // 捐款属于一个捐款人
    app.model.Donation.belongsTo(app.model.User, {
      foreignKey: "donorId",
      as: "donor",
    });
  };

  return Donation;
};
